//
//  LRPhotoChooserController.swift
//  PhotoChooser
//
//  Created by 雷路荣 on 15/12/30.
//  Copyright © 2015年 leilurong. All rights reserved.
//

import UIKit

private let reuseIdentifier = "LRPhotoSelectorCell"

class LRPhotoSelectorController: UICollectionViewController {
    
    //隐藏导航栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    //MARK: - 属性
    /// 用户选择的图片数组
    var photoes = [UIImage]()
    /// 照片最大张数
    private var maxCount = 6
    /// 当前点击cell的indexPath
    private var currentIndexPath: NSIndexPath?
    
    /// 布局
    private var layout = UICollectionViewFlowLayout()
    //MARK: - 构造方法
    init() {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //设置collectionView
        prepareCollectionView()
    }
    ///MARK: - 设置collectionView
    private func prepareCollectionView() {
        //设置背景色
        collectionView?.backgroundColor = UIColor.whiteColor()
        //设置cell大小
        layout.itemSize = CGSizeMake(80, 80)
        //设置组间距
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
        //注册cell
        self.collectionView!.registerClass(LRPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    // MARK: - UICollectionViewDataSource 数据源方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 当图片的数量小于最大张数时,显示照片数+1，用于显示添加按钮
        // 当图片数量等于最大张数时,显示最大张数
        return self.photoes.count < maxCount ? photoes.count + 1 : maxCount
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! LRPhotoSelectorCell
        //设置代理
        cell.delegate = self
        // 让cell显示图片,只有数组里面有图片才显示图片
        if indexPath.item < photoes.count {
            cell.image = photoes[indexPath.item]
        }else {
            // 因为cell的复用,需要重新设置cell为加号按钮
            cell.setAddButton()
        }
        return cell
    }
}

//MARK: - 扩展实现 LRPhotoSelectorCellDelegate 代理方法-------------------------

extension LRPhotoSelectorController: LRPhotoSelectorCellDelegate {
    /// cell里面的加号按钮被点击 参数是告诉代理点击的是哪个cell
    func didClickAddButtonWithCell(cell: LRPhotoSelectorCell) {
        // 获取某个cell的indexPath
        currentIndexPath = collectionView?.indexPathForCell(cell)
        // 1.判断系统的相册是否可用
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            print("系统相册不可用")
            return
        }
        // 2.创建系统的照片选择控制器
        let imagePacker = UIImagePickerController()
        // 3.设置代理,通过这个代理,我们控制器可以知道用户选择了哪张图片
        imagePacker.delegate = self
        // 4.弹出系统的相册来选择图片
        presentViewController(imagePacker, animated: true, completion: nil)
    }
    /// cell里面的删除按钮被点击
    func didClickRemoveButtonWithCell(cell: LRPhotoSelectorCell) {
        // 1.获取点击cell的indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
        // 2.在数组中删除对应的图片
        photoes.removeAtIndex(indexPath!.item)
        // 3.重新刷新数据
        collectionView?.reloadData()
    }
}

//MARK: - 扩展实现 扩展实现系统照片选择器的代理方法-------------------------

extension LRPhotoSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    /// 实现这个方法,就可以知道用户选择了哪张图片,当实现了这个方法后,需要通过代码来关闭控制器
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // 不直接使用原来的图片,将图片缩小.节省内存.节省用户上传图片的流量,将图片等比例缩小的宽度等于300
        let newImage = image.scaleImage()
        print("用户选择了图片: \(newImage)")
        // 将选择的图片添加到数组,如果点击的是加号按钮,添加图片,如果点击的是图片,就修改图片
        // 通过点击的cell的indexPath来判断，点击的是加号还是图片
        if currentIndexPath?.item == photoes.count {
            // 表示点击的是加号,添加图片到数组
            photoes.append(newImage)
        } else {
            // 点击的是图片,替换图片
            photoes[currentIndexPath!.item] = newImage
        }
        // 刷新
        collectionView?.reloadData()
        // 退出
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

//MARK: - 自定义 UICollectionViewCell-----------------------------------------

//MARK: - 定义代理协议   cell点击事件的协议
@objc protocol LRPhotoSelectorCellDelegate: NSObjectProtocol {
    /// cell里面的加号按钮被点击 参数是告诉代理点击的是哪个cell
    optional func didClickAddButtonWithCell(cell: LRPhotoSelectorCell)
    /// cell里面的删除按钮被点击
    optional func didClickRemoveButtonWithCell(cell: LRPhotoSelectorCell)
}

class LRPhotoSelectorCell: UICollectionViewCell {
    
    //MARK: - 属性
    // 代理属性
    weak var delegate: LRPhotoSelectorCellDelegate?
    // cell显示的图片
    var image: UIImage? {
        didSet{
            // 在控制器设置图片后,让加号按钮显示图片
            addButton.setImage(image, forState: UIControlState.Normal)
            // 显示删除按钮
            removeButton.hidden = false
        }
    }
    //MARK: - 构造方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    //MARK: - 准备控件
    func prepareUI() {
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        addButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        //加号按钮
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab": addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab": addButton]))
        //删除按钮，不设置间距不要加 “|”
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["rb": removeButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["rb": removeButton]))
    }
    //MARK: - 设置加号按钮
    func setAddButton() {
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        //隐藏删除按钮
        removeButton.hidden = true
    }
    //MARK: - 按钮点击事件
    //加号按钮点击
    func addButtonClick() {
        // 如果代理实现cellAddButtonClick方法就执行这个方法,如果没有实现这个方法,就不调用这个方法
        delegate?.didClickAddButtonWithCell?(self)//代理方法加“ ？”
    }
    //删除按钮点击
    func removeButtonClick() {
        //代理方法加“ ？”
        delegate?.didClickRemoveButtonWithCell?(self)
    }
    //MARK: - 懒加载
    ///加号按钮
    private lazy var addButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "addButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        //设置显示模式，多余减掉
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        button.sizeToFit()
        return button
    }()
    ///删除图标
    private lazy var removeButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.sizeToFit()
        button.addTarget(self, action: "removeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
}
